package com.yincai.carefreewater.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import com.yincai.carefreewater.R;
import com.yincai.carefreewater.base.BaseActivity;
import com.yincai.carefreewater.callback.StringCallback;
import com.yincai.carefreewater.constant.URLConstant;
import com.yincai.carefreewater.db.SaveDao;
import com.yincai.carefreewater.db.SaveInfo;
import com.yincai.carefreewater.tool.ShareTool;
import com.yincai.carefreewater.tool.ToastTool;
import com.yincai.carefreewater.tool.WindowTool;
import com.yincai.carefreewater.usb.UsbTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 换桶 界面
 */
public class HuanTongActivity extends BaseActivity {
    @BindView(R.id.head_close)
    ImageView headClose;
    @BindView(R.id.huantong_txt)
    TextView huantongTxt;
    @BindView(R.id.huantong_btn)
    Button huantongBtn;
    private String msg_send="";
    private SaveDao saveDao;
private Handler usbHandler =new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        String str=msg.obj.toString();
        switch (msg.what) {
            case -1:
                ToastTool.toast(str);
                break;
            case 0:
                ToastTool.toast(str);
                break;
            case 1:
                try {
                    Log.i(TAG, "换桶Message: " + str);
                    if(str.contains("AT+HT")){
                            finish();
                            stopSound();
                    }else if(str.contains("AT+HTCC")){
                        finish();
                        stopSound();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
        return false;
    }
});
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huantong);
        ButterKnife.bind(this);
        saveDao=new SaveDao(this);
        initSoundpool();//初始化音效
    }

    @Override
    protected void onResume() {
        super.onResume();
        WindowTool.hideMenu(this);
        UsbTool.getInstance().setHandler(usbHandler);
        UsbTool.getInstance().openUsbDevice(HuanTongActivity.this);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                playSound();
            }
        },500);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            UsbTool.getInstance().unRegist();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @OnClick({R.id.head_close, R.id.huantong_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_close:
                finish();
                stopSound();
                break;
            case R.id.huantong_btn:
                msg_send="AT+HT";
                writeToUSb(msg_send);
                finish();
                stopSound();
                break;
        }
    }

    /**
     * 换桶
     */
    private void huantong() {
        AlertDialog.Builder    bu =new AlertDialog.Builder(HuanTongActivity.this);
        bu.setTitle("确认换桶提示!");
        bu.setMessage("确定换桶吗?");
        bu.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
         msg_send="AT+HT";
         writeToUSb(msg_send);
         //通知服务器
         sendHuanTong();
            }
        });
        bu.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        bu.setCancelable(false);
        bu.show();
    }

    /**
     * @param s
     * 往平板写数据
     *
     */
    public void writeToUSb(String s){
        byte[] data = s.getBytes();
        UsbTool.getInstance().writeToUsb(data);
    }
    /**
     *
     * 发送换桶给服务端
     */
    private  void sendHuanTong(){
        String bar_code= ShareTool.getInfo(HuanTongActivity.this,"bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                bar_code = bar.getBarcode();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String path = URLConstant.HOST + URLConstant.DEVICE_REPLACE + "bar_code=" + bar_code ;
        okTool.doGet(path, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onSuccess(Response response, String t) {
                //  Log.i(TAG, "onSuccess: "+t);
                try {
                    JSONObject json=new JSONObject(t);
                    String code = json.optString("code");
                    String msg = json.optString("msg");
                    if(code.equals("100")){
                    }else {
                        ToastTool.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Response response, String errorMsg) {

            }
        });
    }
    /**
     * 初始化 音效
     */
    private SoundPool sp;
    private Map<Integer, Integer> map_sound;
    private void initSoundpool() {
        sp = new SoundPool(1,// 同时播放的音效
                AudioManager.STREAM_MUSIC, 0);
        map_sound = new HashMap<Integer, Integer>();
        int load = sp.load(this, R.raw.didi, 1);
        Log.i(TAG, "initSoundpool: "+load);
        map_sound.put(1, load);
    }
    /**
     * 播放
     */
    int play_id=-1;
    private void playSound() {
        AudioManager am = (AudioManager) getSystemService(this.AUDIO_SERVICE);// 实例化
        float audioMaxVolum = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);// 音效最大值
        float audioCurrentVolum = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        float audioRatio = audioCurrentVolum / audioMaxVolum;
        play_id = sp.play(map_sound.get(1), 1,// 左声道音量
                1,// 右声道音量
                1, // 优先级
                -1,// 循环播放次数
                1);// 回放速度，该值在0.5-2.0之间 1为正常速度
        Log.i(TAG, "playSound: 播放音效"+map_sound.get(1));
    }
    /**
     * 停止音效
     */
    private void stopSound() {
        if(play_id!=-1) {
            sp.pause(play_id);
        }
    }
}
